package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"
	"xiaoniu-registry/internal/cache"
	"xiaoniu-registry/internal/config"
	"xiaoniu-registry/internal/persistence"
	"xiaoniu-registry/internal/router"
)

/**
程序启动入口
*/
func main() {
	// 初始化配置
	cfg := config.InitConfig()

	fmt.Printf("======== Welcome to the xiaoniu-registry ｜ 菜牛注册中心，监听端口为：%d =========\n", cfg.Server.Port)

	// 初始化持久化管理器
	persistenceManager := persistence.InitPersistence(cfg)

	// 设置路由
	mux := router.SetupRoutes()

	// 启动健康检测定时任务
	go cache.DoBackGroundJob()

	// 创建HTTP服务器
	server := &http.Server{
		Addr:         cfg.Server.Host + ":" + strconv.Itoa(cfg.Server.Port),
		Handler:      mux,
		ReadTimeout:  cfg.Server.ReadTimeout,
		WriteTimeout: cfg.Server.WriteTimeout,
	}

	// 启动服务器的goroutine
	go func() {
		log.Printf("Starting server on %s", server.Addr)
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Server failed to start: %v", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutting down server...")

	// 给服务器30秒时间来完成现有请求
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		log.Fatalf("Server forced to shutdown: %v", err)
	}

	// 停止持久化管理器
	if persistenceManager != nil {
		persistenceManager.Stop()
	}

	log.Println("Server exited")
}
